package com.jeasonzhao.commons.parser.expression;

import com.jeasonzhao.commons.utils.DataTypes;
import com.jeasonzhao.commons.parser.lex.LexTokenTypes;

public class SyntaxValueNode extends SyntaxNode
{
    private String valueString = null;
    private LexTokenTypes tokenType=LexTokenTypes.STRING;
    public SyntaxValueNode(LexTokenTypes dt,String valName)
    {
        this.valueString=valName;
        this.tokenType=dt;
    }
    public void replaceVariableName(INameConvertor map)
    {
        if(this.isVariable() && map!=null && this.valueString!=null)
        {
           this.valueString=map.convert(this.valueString);
        }
    }
    public String getExpression()
    {
        if(null == valueString)
        {
            return valueString;
        }
        switch(this.tokenType)
        {
            case STRING:
                return "'" + this.valueString + "'";
            case STRING_QUOTED:
                return "\"" + this.valueString + "\"";
            default:
                return valueString;
        }
    }
    public boolean isVariable()
    {
        return this.tokenType == LexTokenTypes.NAME || this.tokenType == LexTokenTypes.LONG_NAME;
    }
    public ValuePair eval(IEvalProvider provider)
        throws EvalException
    {
        if(null == valueString)
        {
            throw new EvalException("Can not evalutor the empty variable.");
        }
        switch(this.tokenType)
        {
            case BLANK:
                return new ValuePair(this.valueString,DataTypes.STRING);
            case DOUBLE:
                return new ValuePair(this.valueString,DataTypes.DOUBLE);
            case LONG_NAME:
            case NAME:
                if(null == provider)
                {
                    throw new EvalException("Can not get the value of the variable named \"" + this.valueString + "\"," +
                                            "the EvalProvider is null.");
                }
                return provider.evalVariable(this.valueString);
            case NUMBER:
                return new ValuePair(this.valueString,DataTypes.INT);
            case STRING:
            case STRING_QUOTED:
                return new ValuePair(this.valueString,DataTypes.STRING);
            case NULL:
                throw new EvalException("Empty string can not be a variable.");
            case SPECIAL:
                throw new EvalException("Special Characters can not be a variable.");
            case COMMENT_BLOCK:
            case COMMENT_LINE:
                throw new EvalException("Comments can not be a variable.");
            default:
                throw new EvalException("Unknown variable type:" + this.toString());
        }
    }
}
